<template>
  <div class="commentDetail">
    <!-- 评论发起人 -->
    <div class="wrapper">
      <div class="item">
        <div class="itemLeft originatorImg">
          <img :src="Sponsor.portrait" />
        </div>
        <div class="itemRight originatorRight">
          <!-- 用户信息名称 -->
          <div class="itemRightTop">
            <div class="userName">
              <div>{{Sponsor.nick || '好先生'}}</div>
              <div>{{Sponsor.createTime || '51年前'}}</div>
            </div>
            <div class="loveIcon" @click="collectBtn(Sponsor.id,Sponsor.userId,1)">
              <div class="imageBox">
                <img
                  :src="(Sponsor.select)?'https://youyang-cdn.mdshuzhi.com/upload/icon_like_new@2x.png':'https://youyang-cdn.mdshuzhi.com/upload/icon_collect@2x.png'"
                />
              </div>
              <div class="loveText">{{Sponsor.likeNums}}</div>
            </div>
          </div>
          <!-- 评论内容 -->
          <div class="itemRightMiddle">{{Sponsor.content || '神雕侠侣'}}</div>
        </div>
      </div>
    </div>
    <!-- 他人评论 -->
    <div>
      <scroller :on-infinite="infinite" ref="myscroller" class="scroll">
        <div class="wrapper wrapperList">
          <div class="item" v-for="(item,index) in ReplyingPersonList" :key="index">
            <div class="itemLeft">
              <img :src="item.portrait" />
            </div>
            <div class="itemRight">
              <!-- 用户信息名称 -->
              <div class="itemRightTop">
                <div class="userName">
                  <div>{{item.nick||'裘先生'}}</div>
                  <div>{{item.createTime}}</div>
                </div>
                <div class="loveIcon" @click="collectBtn(item.id,item.userId,2)">
                  <div class="imageBox">
                    <img
                      :src="(item.select)?'https://youyang-cdn.mdshuzhi.com/upload/icon_like_new@2x.png':'https://youyang-cdn.mdshuzhi.com/upload/icon_collect@2x.png'"
                    />
                  </div>
                  <div class="loveText">{{item.likeNums}}</div>
                </div>
              </div>
              <!-- 评论内容 -->
              <div
                class="itemRightMiddle"
                @click="focusButn(item.nick,item.id,item.toUserId)"
                data-rid="item.id"
                data-to-user-id="item.toUserId"
              >
                <div v-if="item.toUserNick">
                  回复
                  <span class="otherName">{{item.toUserNick || '西毒欧阳锋'}}</span>
                  :{{item.content||'杨过和姑姑'}}
                </div>
                <div v-else>{{item.content||'杨过和姑姑'}}</div>
              </div>
            </div>
          </div>
        </div>
      </scroller>
    </div>

    <!-- 评论输入框 -->
    <div class="inputBox" :style="'bottom:'+inputBottom+'px'">
      <!-- 注意点：1.style='bottom:{{inputBottom}}px'单位用px
      2.input的 adjust-position='{{false}}'要用false-->
      <input
        type="text"
        class="textInput"
        v-model="content"
        :placeholder="placeholder"
        @focus="foucus"
        @blur="blur"
        @confirm="submit"
        @keyup.13="submit"
        ref="input"
      />
    </div>
  </div>
</template>

<script>
import controller from "@/components/controllers/controllers";
import { getBeforeTime } from "@/utils/filters";
import { Toast, MessageBox } from "mint-ui";
import url from "@/router/http_conf.js";
export default {
  name: "commentDetail",
  components: {},
  data() {
    return {
      loveIconId: 0, //点击点赞爱心按钮
      inputBottom: 0, //用于输入框能键盘弹出使得布局上移
      content: "", //输入框内容,
      focusInput: false,
      Sponsor: {}, //评论发起人
      ReplyingPersonList: [], //回复人
      page: 1,
      pageSize: 10,
      lastPage: null,
      options: {}, //别的页面传来的参数
      bodyId: 1, //type == 5使用，表示评论的对象，具体是1是栏目，2是合辑，3是音频的id,当是一级评论则rid = bodyId
      isCheckCollect: null, //检测点赞收藏返回来的id
      rid: "", //关联的id
      toUserId: "",
      placeholder: "",
    };
  },
  mounted() {
    this.options = this.$route.query;
    this.getCommentDetail();
    this.getCommentList();
    window.addEventListener('mousewheel',this.handleScroll);
  },
  destroyed(){
    window.removeEventListener('mousewheel',this.handleScroll)
  },
  methods: {
    handleScroll(e){
      let that = this  //此this指向的是vue
      console.log(e.wheelDelta)
      if (e.wheelDelta < 0) {
          that.$refs.myscroller && (that.$refs.myscroller.scrollBy(0, 50, true));
      } else {
        that.$refs.myscroller && (that.$refs.myscroller.scrollBy(0, -50, true));
      }
    },
    focusButn(name, id, userId) {
      this.$refs.input.focus();
      this.placeholder = "回复" + name;
      this.bodyId = id;
      this.toUserId = userId;
    },
    foucus() {},
    blur() {
      this.placeholder = "回复" + this.Sponsor.nick;
      this.toUserId = this.Sponsor.userId;
      this.bodyId = this.Sponsor.id;
    },
    submit() {
      console.log("提交");
      let params;
      let _self = this;
      params = {
        content: this.content,
        rid: this.bodyId,
        bodyId: this.options.bodyId,
        type: 5, //评论对象的类型，1是栏目，2是合辑，3是音频，4是评论
        bodyType: this.options.type, //1是栏目，2是合辑，3是音频，4是达人榜
        toUserId: this.toUserId,
      };
      if (this.content == "") {
        Toast("请输入评论内容");
      } else {
        controller.comment(params).then((res) => {
          console.log("评论发送", res);
          Toast("评论成功");
          _self.$updateScore(8)
          _self.content = "";
          _self.page = 1;
          _self.lastPage = false;
          _self.ReplyingPersonList = [];
          _self.getCommentList();
        });
      }
    },
    // 当前用户评论发起人-> 参数id（评论id）
    getCommentDetail() {
      let id = this.options.id;
      let _self = this;
      console.log(this.options);
      controller
        .commentDetail({
          id, //评论id
          token: localStorage.getItem("token"),
        })
        .then((res) => {
          console.log("当前用户评论发起人", res);
          if (res && res.baseData) {
            res.baseData.select = res.baseData.liked == 1 ? true : false;
            res.baseData.likeNums = res.baseData.likeCount;
            res.baseData.createTime = getBeforeTime(res.baseData.createTime);
            _self.Sponsor = res.baseData;
            _self.placeholder = "回复" + _self.Sponsor.nick;
            _self.toUserId = _self.Sponsor.userId;
            _self.bodyId = _self.Sponsor.id;
          }
        });
    },
    // 评论回复人->评论列表 参数page pageSize rid（关联id） type=4
    getCommentList() {
      let _self = this;
      let params = {
        page: this.page,
        pageSize: 10,
        rid: this.options.id, //关联id(音频的id)
        type: 5, //评论对象的类型，1是栏目，2是合辑，3是音频，4是达人榜，5是评论
        token: localStorage.getItem("token"),
      };
      controller.commentList(params).then((res) => {
        console.log("评论列表", res);
        res.baseData.list.map((item) => {
          item.select = item.liked == 1 ? true : false;
          item.likeNums = item.likeCount;
          item.createTime = getBeforeTime(item.createTime);
        });
        _self.ReplyingPersonList = _self.ReplyingPersonList.concat(
          res.baseData.list
        );
        _self.lastPage = res.baseData.lastPage;
        _self.totalRow = res.baseData.totalRow;
      });
    },
    // 上拉加载
    infinite(done) {
      setTimeout(() => {
        if (this.lastPage) {
          console.log(
            "这个方法是不让它加载了，显示“没有更多数据”，要不然会一直转圈圈"
          );
          this.$refs.myscroller.resize();
          this.$refs.myscroller.finishInfinite(true); //这个方法是不让它加载了，显示“没有更多数据”，要不然会一直转圈圈
        } else {
            console.log("进行下一次加载操作");
            this.lastPage = true;
            done(); //进行下一次加载操作
            this.page += 1;
            this.getCommentList();
        }
      }, 500);
    },
    // 检测是否点赞收藏
    checkCollect(rid) {
      let _self = this;
      let flag = true;
      controller
        .checkCollect({
          type: 5,
          rid,
          token: localStorage.getItem("token"),
        })
        .then((res) => {
          console.log(res);
          _self.collectId = res.baseData;
        });
    },
    // 点赞方法
    collectBtn(id, userId, type) {
      let that = this;
      let flag = null;
      // console.log(item.id, e.currentTarget.dataset.id)
      if (type == 1) {
        console.log("type", type);
        this.Sponsor.select = !this.Sponsor.select;
        flag = this.Sponsor.select ? false : true;
        this.Sponsor.likeNums = this.Sponsor.select
          ? this.Sponsor.likeNums + 1
          : this.Sponsor.likeNums - 1;
      } else {
        console.log("type", type);
        this.ReplyingPersonList.map((item) => {
          if (item.id == id) {
            // console.log(item.id, e.currentTarget.dataset.id)
            item.select = item.select ? false : true;
            flag = item.select ? false : true;
            item.likeNums = flag ? item.likeNums - 1 : item.likeNums + 1;
          }
        });
      }
      // 检测当前评论是否传回id
      that.checkCollect(id);
      console.log("flag", flag);
      if (that.timer) {
        clearTimeout(that.timer);
      }
      that.timer = setTimeout(() => {
        if (!flag) {
          that.collectfn(id, userId);
        } else {
          that.delCollectfn(id);
        }
      }, 300);
    },
    // 点赞收藏方法
    collectfn(rid, userId) {
      let that = this;
      let params = {
        rid: rid, //点赞的对象是评论，那rid就是对象的id
        bodyType: this.options.type, //（主体类型）
        bodyId: this.options.bodyId, //音频（或者栏目，合辑等）的id
        toUserId: userId,
        type: 5,
        token: localStorage.getItem("token"),
      };
      controller.collect(params).then((res) => {
        console.log("点赞方法", res);
        that.checkCollect(rid);
        that.$updateScore(9)
      });
    },
    // 取消收藏,点赞
    delCollectfn(rid) {
      let that = this;
      controller
        .delCollect({
          ids: this.collectId,
          token: localStorage.getItem("token"),
        })
        .then((res) => {
          that.checkCollect(rid);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.commentDetail {
  // width: 750px;
  width: 100%;
  min-width: 640px;
  max-width: 960px;
  margin: 0 auto;
  background-color: #f6f6fa;
}

/* 评论输入框 */
.inputBox {
  width: 100%;
  min-width: 640px;
  max-width: 960px;
  margin: 0 auto;
  height: 98px;
  background-color: #fff;
  z-index: 999;
  padding: 15px 24px;
  box-sizing: border-box;
  position: fixed;
  bottom: 0px;
  box-shadow: 0 -1px 5px 1px rgba(0, 0, 0, 0.1);
  border: none;
  left: 50%;
  transform: translateX(-50%);

  .textInput {
    width: 100%;
    height: 68px;
    background-color: #f5f5f5;
    border-radius: 34px;
    color: #999;
    font-size: 28px;
    padding-left: 31px;
    box-sizing: border-box;
    border: none;
  }
}

.scroll {

  position: static !important;
  height: calc(100vh - 350px) !important;
  /deep/ &._v-container{
    top:41px;
    // height: auto !important;
    ._v-content{
      padding-bottom: 40px;
    }
  }
}

.wrapper {
  width: 100%;
  margin-bottom: 20px;
  background-color: #fff;
  padding: 0 43px;
  box-sizing: border-box;

  .item {
    width: 100%;
    display: flex;
    justify-content: space-between;
    margin-bottom: 33px;

    .itemLeft {
      width: 58px;
      margin-right: 12px;

      img {
        width: 58px;
        height: 58px;
        border-radius: 50%;
      }
    }

    .originatorImg {
      width: 70px;
      margin-right: 12px;

      img {
        width: 70px;
        height: 70px;
        border-radius: 50%;
      }
    }

    /* 评论发起人头像 end */
    .itemRight {
      width: 628px;

      .itemRightTop {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .userName {
          div:first-child {
            font-size: 28px;
            color: #333333;
            margin-bottom: 10px;
          }

          div:last-child {
            font-size: 20px;
            color: #a8acbb;
          }
        }

        .loveIcon {
          width: 32px;
          display: flex;
          flex-direction: column;
          align-items: center;

          .imageBox,
          .imageBox img {
            width: 32px;
            height: 32px;
          }
        }
      }
    }

    /* 评论发起人右侧 */
    .originatorRight {
      width: 582px;
    }
  }

  /* 评论内容 */
  .itemRightMiddle {
    width: 100%;
    line-height: 46px;
    font-size: 30px;
    color: #333333;
    margin: 30px 0 20px;
  }
}

.wrapperList {
  // padding-bottom: 100px;
}
</style>
